// ==UserScript==
// @name         鬼火产码前添加上传码按钮
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  在产码按钮前添加一个上传码按钮，并弹出上传窗口
// @author       Tang Yong
// @match        *://pay.god.ghh6.org/LyQixDMrWn.php/acount?*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(function() {
    'use strict';

    // 1. 监听 `产码` 按钮是否出现
    function waitForElements(selector, callback) {
        let interval = setInterval(() => {
            let elements = document.querySelectorAll(selector);
            if (elements.length > 0) {
                clearInterval(interval);
                callback(elements);
            }
        }, 500);
    }

    // 2. 添加 `上传码` 按钮
    function addUploadButton(buttons) {
        buttons.forEach(button => {
            if (!button.dataset.uploadAdded) {  // 防止重复添加
                button.dataset.uploadAdded = "true";

                let uploadBtn = document.createElement("a");
                uploadBtn.innerText = "上传";
                uploadBtn.href = "javascript:void(0);";
                uploadBtn.className = "btn btn-primary btn-xs upload-code-btn";
                uploadBtn.title = "上传";
                uploadBtn.onclick = () => showUploadDialog();

                button.parentNode.insertBefore(uploadBtn, button);
            }
        });
    }

    // 3. 显示上传码弹窗
    function showUploadDialog() {
        let dialog = document.createElement("div");
        dialog.classList.add("upload-dialog");
        dialog.innerHTML = `
            <div class="upload-dialog-content">
                <span class="close-btn">&times;</span>
                <h2>产码上传</h2>
                <label>参数URL</label>
                <input type="text" id="upload-url" placeholder="请输入 URL" value=` + (GM_getValue("uploadUrl") !== undefined ? GM_getValue("uploadUrl") : "") +`>
                <label>订单参数</label>
                <textarea id="upload-order" placeholder="请输入订单参数"></textarea>
                <div class="dialog-buttons">
                    <button id="confirm-upload">确认</button>
                    <button id="cancel-upload">取消</button>
                </div>
            </div>
        `;

        document.body.appendChild(dialog);

        // 关闭弹窗
        dialog.querySelector(".close-btn").onclick = () => dialog.remove();
        dialog.querySelector("#cancel-upload").onclick = () => dialog.remove();

        // 确认上传
        dialog.querySelector("#confirm-upload").onclick = () => {
            let fullUrl = document.getElementById("upload-url").value;
            let orderParam = document.getElementById("upload-order").value;

            if (!fullUrl || !orderParam) {
                alert("请输入完整信息！");
                return;
            }

            // 解析 aid 和 key
            let urlParams = new URLSearchParams(fullUrl.split("?")[1]);
            let aid = urlParams.get("aid");
            let key = urlParams.get("key");

            if (!aid || !key) {
                alert("URL 中必须包含 aid 和 key！");
                return;
            }

            //保存url到local
            GM_setValue("uploadUrl", fullUrl);

            // base64 编码
            let encodedData = btoa(unescape(encodeURIComponent(orderParam)));

            // 构造 body
            let body = `aid=${aid}&key=${key}&base64Str=${encodeURIComponent(encodedData)}`;
            // 提取 URL（去掉参数）
            let postUrl = fullUrl.split("?")[0];
            // 发送 POST 请求
            sendPostRequest(postUrl, body);
            dialog.remove();
        };
    }

    function sendPostRequest(url, body) {
        console.log("发送请求到:", url);
        console.log("请求体:", body);

        GM_xmlhttpRequest({
            method: "POST",
            url: url,
            headers: {
                "User-Agent": "python-requests/2.28.2",
                "Accept-Encoding": "gzip, deflate",
                "Accept": "*/*",
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: body,
            onload: function(response) {
                alert("请求成功！服务器返回：" + response.responseText);
            },
            onerror: function(error) {
                alert("请求失败！请检查网络或服务器状态");
            }
        });
    }

    // 4. 添加样式
    GM_addStyle(`
        .upload-code-btn {
            margin-right: 5px;
            background: #007bff;
            color: white !important;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            border-radius: 4px;
            text-decoration: none;
        }
        .upload-code-btn:hover {
            background: #0056b3;
        }
        .upload-dialog {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 8px;
            z-index: 1000;
            width: 300px;
        }
        .upload-dialog-content {
            display: flex;
            flex-direction: column;
        }
        .upload-dialog-content label {
            margin-top: 10px;
        }
        .upload-dialog-content input, .upload-dialog-content textarea {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .dialog-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
        }
        .dialog-buttons button {
            padding: 5px 10px;
            border: none;
            cursor: pointer;
            border-radius: 4px;
        }
        #confirm-upload {
            background: #28a745;
            color: white;
        }
        #confirm-upload:hover {
            background: #218838;
        }
        #cancel-upload {
            background: #dc3545;
            color: white;
        }
        #cancel-upload:hover {
            background: #c82333;
        }
        .close-btn {
            position: absolute;
            top: 5px;
            right: 10px;
            cursor: pointer;
            font-size: 18px;
        }
    `);

    // 5. 监测 `产码` 按钮
    waitForElements("a.btn.btn-primary.btn-refresh", addUploadButton);

})();